package com.tuanzi.loan.business.repository.family.impl;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanUserCreditRecord.LOAN_USER_CREDIT_RECORD;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanUserFaceInfo.LOAN_USER_FACE_INFO;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanUserInfo.LOAN_USER_INFO;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanXfUserInfo.LOAN_XF_USER_INFO;

import org.apache.commons.lang3.StringUtils;
import org.jooq.*;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import com.tuanzi.loan.business.analyzer.BaiduJRAnalyzer;
import com.tuanzi.loan.business.entity.family.UserCreditRecordSourceType;
import com.tuanzi.loan.business.repository.family.custom.UserInfoRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.generated.jooq.loan.tables.LoanUserCreditRecord;
import com.tuanzi.loan.generated.jooq.loan.tables.LoanUserInfo;
import com.tuanzi.loan.vo.request.family.UserInfoSearchRequest;
import com.tuanzi.loan.vo.response.family.UserInfoSearchResponse;

/**
 * @author Ray 2017/09/21
 * 添加 FaceId认证、是否有信用卡、运营商授权 的搜索条件
 * @author JinRuiyang 2018/01/11
 */
@SuppressWarnings({ "rawtypes" })
@Repository
public class UserInfoRepositoryCustomImpl extends JOOQBaseRepositoryPlus implements UserInfoRepositoryCustom {

    private static final int AuthFailed = 0;
    private static final int AuthPassed = 1;
    private static final int NotAuthed  = 2;


    private static final int HaceNoCredit = 0;
    private static final int HaveCredit = 1;
    private static final int NoCreditInfo  = 2;

	@Override
	protected LoanUserInfo getTable() {
		return LOAN_USER_INFO;
	}

	@Autowired
	private BaiduJRAnalyzer baiduJRAnalyzer;

    @Override
    public Boolean getUserFaceAuthResult(Long userId) {
        return dslContext.select(LOAN_USER_FACE_INFO.IS_PASS)
                .from(LOAN_USER_FACE_INFO)
                .where(LOAN_USER_FACE_INFO.USERID.eq(userId))
                .fetchOne(LOAN_USER_FACE_INFO.IS_PASS.cast(Boolean.class));
    }

    @Override
    public String getUserPhoneContactJson(Long userId) {
        return dslContext.select(LOAN_XF_USER_INFO.PHONE_BOOK)
                .from(LOAN_XF_USER_INFO)
                .where(LOAN_XF_USER_INFO.USERID.eq(userId))
                .fetchOne(LOAN_XF_USER_INFO.PHONE_BOOK);
    }

    @Override
	public Page<UserInfoSearchResponse> list(UserInfoSearchRequest searchRequest, Pageable pageable) {
        LoanUserCreditRecord lucrJR = LOAN_USER_CREDIT_RECORD.as("LUCR_JR");
        SelectJoinStep joinStep = dslContext.select(getTable().fields()).select(lucrJR.TEXT1.as("BAIDU_JR_LEVEL")).from(getTable());
        // 百度金融命中
        joinStep = joinStep.leftJoin(lucrJR)
                .on(lucrJR.USER_NAME.eq(getTable().PETNAME))
                .and(lucrJR.PHONE.eq(getTable().MOBNUM))
                .and(lucrJR.IDCARD.eq(getTable().IDCARD))
                .and(lucrJR.SOURCE_TYPE.eq(UserCreditRecordSourceType.BAIDU_JR.name()));
        // FaceId认证 通过未通过判断
        if (searchRequest.getFaceIdAuth() != null && (searchRequest.getFaceIdAuth() == AuthPassed || searchRequest.getFaceIdAuth() == AuthFailed)){
            joinStep = joinStep.join(LOAN_USER_FACE_INFO)
                    .on(LOAN_USER_FACE_INFO.USERID.eq(getTable().USERID))
                    .and(LOAN_USER_FACE_INFO.IS_PASS.eq((byte)searchRequest.getFaceIdAuth().intValue()));
        }
        // 运营商授权 通过未通过判断
        if (searchRequest.getIspAuth() != null && (searchRequest.getIspAuth() == AuthPassed || searchRequest.getIspAuth() == AuthFailed)){
            Condition ispAuth;
            if (searchRequest.getIspAuth() == AuthPassed)
                ispAuth = LOAN_USER_CREDIT_RECORD.TEXT1.isNotNull().or(LOAN_USER_CREDIT_RECORD.TEXT2.isNotNull());
            else
                ispAuth = LOAN_USER_CREDIT_RECORD.TEXT1.isNull().and(LOAN_USER_CREDIT_RECORD.TEXT2.isNull());
            joinStep = joinStep.join(LOAN_USER_CREDIT_RECORD)
                    .on(LOAN_USER_CREDIT_RECORD.USER_NAME.eq(getTable().PETNAME))
                    .and(LOAN_USER_CREDIT_RECORD.PHONE.eq(getTable().MOBNUM))
                    .and(LOAN_USER_CREDIT_RECORD.IDCARD.eq(getTable().IDCARD))
                    .and(LOAN_USER_CREDIT_RECORD.SOURCE_TYPE.eq("BAIDU_YYS"))
                    .and(ispAuth);
        }
        // 运营商授权 无数据判断
		SelectConditionStep sql = joinStep.where(DSL.trueCondition());
        if (searchRequest.getIspAuth() != null && searchRequest.getIspAuth() == NotAuthed){
            sql = sql.andNotExists(dslContext.select(LOAN_USER_CREDIT_RECORD.ID)
                            .from(LOAN_USER_CREDIT_RECORD)
                            .where(LOAN_USER_CREDIT_RECORD.USERID.eq(getTable().USERID)));
        }
        // FaceId认证 无数据判断
        if (searchRequest.getFaceIdAuth() != null && searchRequest.getFaceIdAuth() == NotAuthed){
            sql = sql.andNotExists(dslContext.select(LOAN_USER_FACE_INFO.ID)
                            .from(LOAN_USER_FACE_INFO)
                            .where(LOAN_USER_FACE_INFO.USERID.eq(getTable().USERID)));
        }
        // 信用卡判断
        Integer isHaveCredit = searchRequest.getIsHaveCredit();
        if (isHaveCredit != null && (isHaveCredit == HaceNoCredit ||isHaveCredit == HaveCredit || isHaveCredit == NoCreditInfo)){
            Condition credit;
            if (isHaveCredit == HaceNoCredit)
                credit = getTable().CREDIT.eq("0")
                        .or(getTable().CREDIT.eq("no"))
                        .or(getTable().CREDIT.eq("否"))
                        .or(getTable().CREDIT.eq("没有"));
            else if (isHaveCredit == HaveCredit)
                credit = getTable().CREDIT.eq("1")
                        .or(getTable().CREDIT.eq("是"))
                        .or(getTable().CREDIT.eq("有"));
            else
                credit = getTable().CREDIT.isNull();
            sql = sql.and(credit);
        }
        // 原先业务判断
		if (StringUtils.isNotBlank(searchRequest.getPetname()))
			sql = sql.and(getTable().PETNAME.contains(searchRequest.getPetname()));
		if (StringUtils.isNotBlank(searchRequest.getMobnum()))
			sql = sql.and(getTable().MOBNUM.contains(searchRequest.getMobnum()));
		if (StringUtils.isNotBlank(searchRequest.getIdcard()))
			sql = sql.and(getTable().IDCARD.contains(searchRequest.getIdcard()));
		if (StringUtils.isNotBlank(searchRequest.getUserId()))
			sql = sql.and(getTable().USERID.eq(Long.parseLong(searchRequest.getUserId())));
		if (StringUtils.isNotBlank(searchRequest.getProfession()))
			sql = sql.and(getTable().PROFESSION.eq(searchRequest.getProfession()));
        return search(sql.getQuery(), pageable, new UserInfoSearchResponseRecordMapper());
	}

	private final class UserInfoSearchResponseRecordMapper implements RecordMapper<Record, UserInfoSearchResponse> {
		@Override
		public UserInfoSearchResponse map(Record record) {
			UserInfoSearchResponse response = new UserInfoSearchResponse();
			response.setId(record.get(LOAN_USER_INFO.ID));
			response.setUserId(record.get(LOAN_USER_INFO.USERID));
			response.setCredit(record.get(LOAN_USER_INFO.CREDIT));
			response.setIdcard(record.get(LOAN_USER_INFO.IDCARD));
			response.setMobnum(record.get(LOAN_USER_INFO.MOBNUM));
			response.setPetname(record.get(LOAN_USER_INFO.PETNAME));
			response.setProfession(record.get(LOAN_USER_INFO.PROFESSION));
			response.setSesamePoint(record.get(LOAN_USER_INFO.SESAME_POINT));
			response.setBaiduJRLevel(baiduJRAnalyzer.getBlackLevel(record.get("BAIDU_JR_LEVEL") == null ? StringUtils.EMPTY : record.get("BAIDU_JR_LEVEL").toString()));
			return response;
		}
	}
}
